from flask import current_app
from flask import g
from flask import redirect
from flask import render_template
from flask import request
from flask import session
from flask import url_for

from info import user_login_data
from info.models import User
from . import admin_blu


@admin_blu.route("/login", methods=["GET","POST"])
def admin_login():
    """管理员登陆页面[作业]"""
    if request.method == "GET":
        return render_template("admin/login.html")

    else:
        ''' 接收登陆信息 '''
        data_dict = request.form
        mobile = data_dict.get("mobile")
        password = data_dict.get("password")

        # 校验参数
        if not all([mobile, password]):
            return render_template('admin/login.html', errmsg="参数不足")

        try:
            user = User.query.filter(User.mobile == mobile).first()
        except Exception as e:
            current_app.logger.error(e)
            return render_template('admin/login.html', errmsg="数据查询失败")

        if not user:
            return render_template('admin/login.html', errmsg="用户不存在")

        if not user.check_passowrd(password):
            return render_template('admin/login.html', errmsg="密码错误")

        if not user.is_admin:
            return render_template('admin/login.html', errmsg="用户权限错误")

        # 登陆成功
        session["user_id"] = user.id
        session["nick_name"] = user.nick_name
        session["mobile"] = user.mobile
        session["is_admin"] = True

        # 跳转页面
        return redirect(url_for("admin.index"))


@admin_blu.route("/")
@user_login_data
def index():
    """admin后台首页"""
    user = g.user
    # 因为我们已经在请求钩子中设置只有登陆才能访问到后台admin站点，所以我们不需要再次判断了。
    return render_template("admin/index.html",
                           user=user
                           )
